package net.muchine.core.support.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;

import net.muchine.core.support.Codes;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Converter {
	@Autowired private Codes codes;
	
	public void setCodes(Codes codes) {
		this.codes = codes;
	}
	
	public String convertDateWithTimeZone(Date date, String timezone) {
		if (date == null) return null;

		SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm");
		
		if (timezone != null && timezone.length() > 0) {
			Map<String, String> timezones = codes.getTimeZoneList();
			String description = timezones.get(timezone);
			if (description == null) throw new IllegalArgumentException("paramter timezone is invalid.");
			
			int offset = 0;
			char indicator = description.charAt(4);
			if (indicator == '+')
				offset = Integer.parseInt(description.substring(5, 7)) * 3600000;
			else 
				offset = Integer.parseInt(description.substring(4, 7)) * 3600000;
			
			df.setTimeZone(TimeZone.getTimeZone(TimeZone.getAvailableIDs(offset)[0]));
		}
				
		return df.format(date);
	}
	
	public static void main(String[] args) {
		Converter converter = new Converter();
		converter.setCodes(new Codes());
		
		Date date = new Date();
		System.out.println(converter.convertDateWithTimeZone(date, "Bogota"));
		System.out.println(converter.convertDateWithTimeZone(date, "London"));
		System.out.println(converter.convertDateWithTimeZone(date, "Seoul"));
	}
}
